package com.ruoyi.framework.oss.factory;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.oss.constant.OssConstant;
import com.ruoyi.framework.oss.core.OssClient;
import com.ruoyi.framework.oss.exception.OssException;
import com.ruoyi.framework.oss.properties.OssProperties;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zouhuu
 * @description 文件上传Factory
 * @date 2022/07/24 20:56:43
 */
public class OssFactory {

    private static final Map<String, OssClient> CLIENT_CACHE = new ConcurrentHashMap<>();


    /**
     * 初始化工厂
     */
    public static void init() {
        String configKey = SpringUtils.getBean(RedisCache.class).getCacheObject(CacheConstants.CACHE_CONFIG_KEY).toString();

    }

    /**
     * 获取默认实例
     */
    public static OssClient instance() {
        // 获取redis 默认类型
        String configKey = SpringUtils.getBean(RedisCache.class).getCacheObject(OssConstant.CACHE_CONFIG_KEY).toString();
        if (StringUtils.isEmpty(configKey)) {
            throw new OssException("文件存储服务类型无法找到!");
        }
        return instance(configKey);
    }

    /**
     * 根据类型获取实例
     */
    public static OssClient instance(String configKey) {
        OssClient client = getClient(configKey);
        if (client == null) {
            refresh(configKey);
            return getClient(configKey);
        }
        return client;
    }

    private static void refresh(String configKey) {

        String jsonstr = SpringUtils.getBean(RedisCache.class).getCacheObject(OssConstant.SYS_OSS_KEY + configKey).toString();
        OssProperties properties =  JSONUtil.toBean(jsonstr, OssProperties.class);
        if (properties == null) {
            throw new OssException("系统异常, '" + configKey + "'配置信息不存在!");
        }
        CLIENT_CACHE.put(configKey, new OssClient(configKey, properties));
    }

    private static OssClient getClient(String configKey) {
        return CLIENT_CACHE.get(configKey);
    }



}
